import Vue from 'vue'
import VueRouter from 'vue-router'
import { storageGet } from '@/storage'
import config from '@/config'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Users from '@/components/Users'
import Welcome from '@/components/Welcome'
import Rights from '@/components/power/Rights'
import Roles from '@/components/power/Roles'
import GoodsList from '@/components/goods/GoodsList'
import Cates from '@/components/goods/Cates'
Vue.use(VueRouter) // 这一步不能少注册

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      children: [
        // 当二级路由的path为空的时候，会作为默认展示内容
        { path: '', component: Welcome },
        {
          path: '/users',
          component: Users
        },
        {
          path: '/rights',
          component: Rights
        },
        {
          path: '/roles',
          component: Roles
        },
        {
          path: '/goods',
          component: GoodsList
        },
        {
          path: '/categories',
          component: Cates
        }
      ]
    }
  ]
})

// 挂载路由守卫,就是一个钩子函数
// router.beforeEach((to, from, next) => {
//   // to 将要访问的路径
//   // from 从哪个路径跳转而来
//   // next 是一个函数，表示放行
//   // next() 放行 next('/longin') 强制跳转
//   if (to.path === '/login') return next()
//   // 获取token
//   const tokenStr = storageGet(config.SignName)
//   if (!tokenStr) return next('/login')
//   next()
// })
router.beforeEach(({ path }, from, next) => {
  if (path === '/login') {
    return next()
  }
  const token = storageGet(config.SignName)
  if (!token) {
    return next('/')
  } else {
    next()
  }
})

export default router
